<template>
  <div class="login">
    <div class="box">
      <el-form
      :model="userInfo"
      label-width='80px'
      :rules="rules"
      ref="formRef"
     >
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="userInfo.username" type="text"/>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model="userInfo.password"
            type="password"
          />
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button type="primary" @click = "loginHandle">登录</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
// 验证密码框规则
function passRules (rule, value, callback) {
  if (value === '') {
    callback(new Error('请填写密码'))
  } else if (!/^\w{5,12}$/.test(value)) {
    callback(new Error('请填写 5 ~ 12 位'))
  } else {
    callback()
  }
}
export default {
  name: 'oaLogin',
  data () {
    return {
      userInfo: {},
      // 输入用户名密码框验证
      rules: {
        username: [
          { required: true, message: '请输入用户名!', trigger: 'change' },
          { min: 5, max: 12, message: '用户名请输入5-12位!', trigger: 'change' }
        ],
        password: [
          { validator: passRules, trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 登录请求
    loginHandle () {
      this.$refs.formRef.validate(async valid => {
        console.log(valid)
        if (!valid) {
          ElMessage({
            showClose: true,
            message: '请正确输入表单内容！~',
            type: 'error'
          })
        }
        const loginRes = await this.$http.post('login', this.userInfo)
        if (loginRes.meta?.status !== 200) {
          ElMessage({
            showClose: true,
            message: '用户名或密码错误！',
            type: 'error'
          })
          return
        }
        window.sessionStorage.setItem('token', loginRes.data.token)
        window.sessionStorage.setItem('user_id', loginRes.data.id)

        ElMessage({
          showClose: true,
          message: '登录成功，即将跳转到首页！',
          type: 'success'
        })
        setTimeout(() => {
          this.$router.push('/home')
        }, 2000)
      })
    },
    // 重置按钮
    resetHandle () {
      this.$refs.formRef.resetFields()
    }
  }
}</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background-color: skyblue;
  overflow: hidden;
  position: relative;
  .box {
    width: 400px;
    height: 250px;
    border-radius: 8px;
    padding:20px;
    box-sizing: border-box;
    background-color: #eee;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .el-button{
    width: 70px;
    height: 30px;
    margin-top: 10px;
  }
}
</style>
